//
//  CustomerInfoChangePasswordViewController.m
//  CPICApp
//
//  Created by sinosoft on 13-5-13.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "CustomerInfoChangePasswordViewController.h"
#import "RCAlertViewUtil.h"
#import "RegexKitLite.h"
#import "NSString+SBJson.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "IFServiceEvaluation.h"
#import "ASIFormDataRequest.h"
#import "LoginViewController.h"

@interface CustomerInfoChangePasswordViewController ()

@end

@implementation CustomerInfoChangePasswordViewController
@synthesize TableCustomer,txtOldPassword,txtNewPassword,txtIdenPassword;
@synthesize UpdateInfoImage,progress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title=@"客户资料密码修改";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"客户资料密码修改");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"客户资料密码修改");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"客户资料密码修改");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }

    //添加UITableview
    arrTitle2=[[NSMutableArray alloc]initWithObjects:@"旧密码:",@"新密码:",@"密码确认:",nil];
    TableCustomer = [[UITableView alloc]initWithFrame:CGRectMake(8, 80, 310, self.view.frame.size.height-44-80) style:UITableViewStyleGrouped];
	TableCustomer.delegate = self;
	TableCustomer.dataSource = self;
    
    TableCustomer.opaque = NO;
    TableCustomer.backgroundView = nil;
    TableCustomer.autoresizingMask = UIViewContentModeTop;
    TableCustomer.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableCustomer.backgroundColor=[UIColor clearColor];
    TableCustomer.scrollEnabled=NO;
    TableCustomer.showsHorizontalScrollIndicator=YES;
	[self.view addSubview:TableCustomer];

    txtOldPassword=[[UITextField alloc]initWithFrame:CGRectMake(105, 5, 185, 40)];
    txtOldPassword.borderStyle=UITextBorderStyleRoundedRect;
    txtOldPassword.delegate=self;
    txtOldPassword.returnKeyType=UIReturnKeyDone;
    txtOldPassword.secureTextEntry=YES;
    txtOldPassword.font = [UIFont systemFontOfSize:16.0];
    
    txtNewPassword=[[UITextField alloc]initWithFrame:CGRectMake(105, 5, 185, 40)];
    txtNewPassword.borderStyle=UITextBorderStyleRoundedRect;
    txtNewPassword.delegate=self;
    txtNewPassword.returnKeyType=UIReturnKeyDone;
    txtNewPassword.secureTextEntry=YES;
    txtNewPassword.font = [UIFont systemFontOfSize:16.0];
    
    txtIdenPassword=[[UITextField alloc]initWithFrame:CGRectMake(105, 5, 185, 40)];
    txtIdenPassword.borderStyle=UITextBorderStyleRoundedRect;
    txtIdenPassword.delegate=self;
    txtIdenPassword.returnKeyType=UIReturnKeyDone;
    txtIdenPassword.secureTextEntry=YES;
    txtIdenPassword.font = [UIFont systemFontOfSize:16.0];


    UpdateInfoImage = [[UIImageView alloc]init];
    UpdateInfoImage.image = [UIImage imageNamed:@"Submit_suggestion.png"];
    UIButton *UpdateInfoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [UpdateInfoBtn setImage:UpdateInfoImage.image forState:UIControlStateNormal];
    UpdateInfoBtn.frame = CGRectMake((self.view.frame.size.width-UpdateInfoImage.image.size.width/2)/2,330, UpdateInfoImage.image.size.width/2, UpdateInfoImage.image.size.height/2);
    [UpdateInfoBtn setTitle:@"修改密码" forState:UIControlStateNormal];
    [UpdateInfoBtn addTarget:self action:@selector(changePassword) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:UpdateInfoBtn];
    
    UILabel * lbUpdate = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-UpdateInfoImage.image.size.width/2)/2, 330-13, UpdateInfoImage.image.size.width/2, UpdateInfoImage.image.size.height/2)];
    lbUpdate.text = @"修改密码";
    lbUpdate.textAlignment = UITextAlignmentCenter;
    lbUpdate.textColor = [UIColor whiteColor];
    lbUpdate.backgroundColor = [UIColor clearColor];
    [self.view addSubview:lbUpdate];
    [lbUpdate release];


}
-(void)changePassword
{
    if (self.txtOldPassword.text == NULL||self.txtOldPassword==nil)
    {
        [self justShowMessage:@"先填写旧密码" title:@"提示"];
        return;
    }
    
    if (self.txtNewPassword.text == NULL||self.txtNewPassword==nil)
    {
        [self justShowMessage:@"先填写新密码" title:@"提示"];
        return;
    }
    
    if (self.txtIdenPassword.text == NULL||self.txtIdenPassword==nil)
    {
        [self justShowMessage:@"先填写密码确认" title:@"提示"];
        return;
    }
    
    if (self.txtNewPassword.text.length>0 && self.txtIdenPassword.text.length>0)
    {
        if (![self.txtNewPassword.text isEqualToString:(self.txtIdenPassword.text)])
        {
            [self justShowMessage:@"两次密码输入不一致" title:@"提示"];
            return;
        }
        
    }
    
    [self setRequest];

}
-(void) ClickCallOutBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Identifier=@"Identifier";
    UITableViewCell *cell=(UITableViewCell *)[TableCustomer dequeueReusableCellWithIdentifier:Identifier];
    UILabel *lblUserAccount;
    
    
    if (cell==nil)
    {
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;//选中后颜色没变化
        lblUserAccount=[[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 85, 21)]autorelease];
        lblUserAccount.backgroundColor=[UIColor clearColor];
        lblUserAccount.font = [UIFont systemFontOfSize:16.0];
        lblUserAccount.tag=111;
        [cell addSubview:lblUserAccount];
        
    }
    
    UIButton * Remindbtn = [UIButton buttonWithType:UIButtonTypeInfoDark];
    Remindbtn.frame = CGRectMake(85, 7, 18, 19);
    [Remindbtn addTarget:self action:@selector(remindclick:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:Remindbtn];
    UILabel *lblUserAccount111=(UILabel *)[cell viewWithTag:111];
    lblUserAccount111.text=[arrTitle2 objectAtIndex:indexPath.row];
    
        if(indexPath.row==0)
        {
            [cell addSubview:txtOldPassword];
            FlagStr1 = @"1";
            Remindbtn.tag = FlagStr1.intValue;
        }
        else if(indexPath.row==1)
        {
            [cell addSubview:txtNewPassword];
            FlagStr2 = @"2";
            Remindbtn.tag = FlagStr2.intValue;
        }
        else if(indexPath.row==2)
        {
            [cell addSubview:txtIdenPassword];
            FlagStr3 = @"3";
            Remindbtn.tag = FlagStr3.intValue;
        }
      
    return cell;


}
-(void) remindclick:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    if (button.tag == FlagStr1.intValue)
    {
        [self justShowMessage:@"请输入当前有效的密码，修改密码时，需要验证旧密码信息" title:@"系统提示!"];
    }
    else if (button.tag == FlagStr2.intValue)
    {
        [self justShowMessage:@"请设置新的登录密码" title:@"系统提示!"];
    }
    else if (button.tag == FlagStr3.intValue)
    {
        [self justShowMessage:@"请再次输入新密码，如果密码确认的内容和新密码不一致时报错。并要求重新输入密码。" title:@"系统提示!"];
    }
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField==txtOldPassword)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else if(textField==txtNewPassword)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else if(textField==txtIdenPassword)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }

    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
-(void)setRequest//向太保移动平台发送请求报文
{
 
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil)
    {
        if ([dictUserInfo valueForKey:@"UserAccount"])
        {
        }
    }
    else
    {
        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
        return;
    }
    NSString *UserAccount=[dictUserInfo valueForKey:@"UserAccount"];
    
    NSString *strRequestData=[NSString stringWithFormat:@"{\"userAccount\":\"%@\",\"newPassword\":\"%@\",\"oldPassword\":\"%@\"}",UserAccount,txtNewPassword.text,txtOldPassword.text];
    NSLog(@"客户资料密码修改请求报文%@",strRequestData);
    
    
    NSString *urlString = [NSString stringWithFormat:Server_Url_Form];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"63501" forKey:@"RequestCode"];
    [request setPostValue:strRequestData forKey:@"RequestData"];
    //[request startSynchronous];
    
	//设置表单提交项
    [request setDelegate:self];

    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress)
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"加载中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"客户资料请求报文responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSMutableDictionary *jsonoSubObj = [dictResponse objectForKey:@"head"];
    NSString * ss = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"success"]];
    if ([ss isEqualToString:@"1"])
    {
        UIAlertView *myAlert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"密码修改成功,请重新登录系统" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        myAlert.tag=1001;
        [myAlert show];
        [myAlert release];
    }
    else
    {
        [self justShowMessage:[jsonoSubObj objectForKey:@"message"] title:@"提示"];
    }
}
- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //清空缓存数据
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    [myDefaults setObject:nil forKey:DICT_USER_INFO];
    [myDefaults synchronize];
    LoginViewController *loginViewCtrl=[[LoginViewController alloc]init];
    [self.navigationController pushViewController:loginViewCtrl animated:YES];
    [loginViewCtrl release];
    //
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    [arrTitle2 release];
    [txtOldPassword release];
    [txtNewPassword release];
    [txtIdenPassword release];
    [UpdateInfoImage release];
    [super dealloc];
}
@end

